package com.demo.interview.abcabc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 现在两个线程，可以操作初始值为0的变量，实现一个线程对该变量+1，一个线程从对该变量-1，实现交替，来10轮，变量初始值为0
 * @author shenguangyang
 */
public class ProdConsumer_Condition {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition conditionInc = lock.newCondition();
    private final Condition conditionDec= lock.newCondition();
    private int number = 0;

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                conditionInc.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            conditionDec.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0){
                conditionDec.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            conditionInc.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ProdConsumer_Condition prodConsumerSync = new ProdConsumer_Condition();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}
